//
//  LLGRefreshControl.swift
//  下拉刷新
//
//  Created by 李龙 on 16/8/14.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit
//视图高度
let LLGRefreshControlHeight: CGFloat = 50

//刷新状态
enum LLGRefreshControlType: Int {

    //下拉刷新
    case Normal = 0
    //将要刷新
    case Pulling = 1
    //正在刷新
    case Refreshing = 2
    
}

class LLGRefreshControl: UIControl {
    //当前滚动视图
    var currentScrollView: UIScrollView?
    
    //刷新状态
    var refreshState: LLGRefreshControlType = .Normal {
    
        didSet {
            switch refreshState {
            //下拉刷新状态
            case .Normal:
                messageLabel.text = "下拉刷新"
                
                //显示箭头,开启转动
                iconImageView.hidden = false
                indicatorView.stopAnimating()
                
                //箭头指向原来位置
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing {
                
                    //进入默认位置,设置滚动视图位置,  (-自身高度)
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= LLGRefreshControlHeight
                    })
                }
            
            //将要刷新状态
            case .Pulling:
                messageLabel.text = "松手就刷新"
                //箭头旋转180
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            //正在刷新状态
            case .Refreshing:
                messageLabel.text = "正在刷新"
                
                //隐藏箭头,开启动画
                iconImageView.hidden = true
                indicatorView.startAnimating()
                
                //正在刷新状态,设置滚动视图停留位置, (+自身高度)
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += LLGRefreshControlHeight
                })
                
                //正在刷新状态,发送事件通知
                sendActionsForControlEvents(.ValueChanged)
            }
            
            
            
        }
    }

    //箭头
    private lazy var iconImageView: UIImageView = {
    
        let view = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        return view
    }()
    //菊花
    private lazy var indicatorView: UIActivityIndicatorView = {
    
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.blueColor()
        return view
        
    }()
    //文字信息
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel()
        label.text = "下拉刷新"
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.grayColor()
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: --添加控件,设置约束
    private func setupUI() {
    
//        backgroundColor = UIColor.redColor()
        
        //添加控件
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        //使用系统约束
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        //设置约束
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: indicatorView, attribute: .Trailing, multiplier: 1, constant: 10))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //判断是否是滚动视图
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
//        scrollView.contentOffset.y
        
        //设置frame
        self.frame.size.width = scrollView.frame.size.width
        self.frame.size.height = LLGRefreshControlHeight
        self.frame.origin.y = -LLGRefreshControlHeight
        
        //kvo监听滚动视图的contentOffset的改变,关注新值
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        
        //记录
        currentScrollView = scrollView
        
    }
    
    // MARK: --kvo方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //是否为记录视图
        guard let scrollView = currentScrollView else {
            return
        }
        
        //获取滚动视图y的偏移量
        let contentOffsetY = scrollView.contentOffset.y
        
        //获取临界点
        let maxY = -(scrollView.contentInset.top + LLGRefreshControlHeight)
        
        //如果在拖拽状态下
        if scrollView.dragging {
        
            //如果位移量小于临界点且进入之前是在下拉刷新状态
            if contentOffsetY < maxY && refreshState == .Normal {
                //将要刷新
                refreshState = .Pulling
                //偏移量大于等于临界点,且进入之前是在将要刷新状态
            } else if contentOffsetY >= maxY && refreshState == .Pulling {
                //  下拉刷新
                refreshState = .Normal
            }
            
        } else {
            
            //不在拖拽且在将要刷新状态时进入正在刷新
            if refreshState == .Pulling {
            
                refreshState = .Refreshing
            }
        }
        
    }
    
    // MARK: --结束刷新,返回默认状态
    func endRefreshing() {
    
        refreshState = .Normal
    }
    
    deinit {
        //移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
